package com.example.rbacmanage.controller.app;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.app.Blog;
import com.example.rbacmanage.service.app.BlogService;
import com.example.rbacmanage.vo.PlaceOnFileResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.Year;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app/blog")
public class AppBlogController {
    @Autowired
    private BlogService blogService;

    @GetMapping("/list")
    public Result page(Blog blog){
        return Result.success(blogService.getPage(blog));
    }

    @GetMapping("/alllist")
    public Result alllist(Blog blog){
        return Result.success(blogService.getAll(blog));
    }

    @GetMapping("/placeOnFile")
    public Result placeOnFile(Blog blog){
        List<Blog> list = blogService.getListOrderByCreateTimeDesc(blog);
        //获取年
        List<Integer> years = new ArrayList<>();
        List<PlaceOnFileResp> last = new ArrayList<>();
        for (Blog b : list) {
            int year =  DateUtil.year(b.getCreateTime());
            if (!years.contains(year)){
                List<PlaceOnFileResp.PlaceOnFileChildren> children = new ArrayList<>();
                for (Blog b2 : list) {
                    int year2 = DateUtil.year(b2.getCreateTime());
                    if (year == year2) {
                        PlaceOnFileResp.PlaceOnFileChildren child = new PlaceOnFileResp.PlaceOnFileChildren();
                        child.setTitle(b2.getTitle());
                        int month = DateUtil.month(b2.getCreateTime())+1;
                        int day = DateUtil.dayOfMonth(b2.getCreateTime());
                        child.setDate(month+"月"+day+"日");
                        child.setId(b2.getId());
                        children.add(child);
                    }
                }
                PlaceOnFileResp resp = new PlaceOnFileResp();
                resp.setChildren(children);
                resp.setYear(year);
                last.add(resp);
                years.add(year);
            }
        }
        return Result.success(last);
    }

    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Long id){
        return Result.success(blogService.getById(id));
    }

    @GetMapping("/eyes/{id}")
    public Result eyes(@PathVariable Long id){
        Blog blog = blogService.getById(id);
        if (blog.getEyes() == null){
            blog.setEyes(0);
        }
        blog.setEyes(blog.getEyes()+1);
        blogService.update(blog);
        return Result.success();
    }
}
